from datetime import datetime

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import logging
import sys
from contextlib import asynccontextmanager

from app.core.config.settings import settings
from app.core.config.database import engine, Base
from app.api.v1 import services
from app.services.monitoring.scheduler import start_health_monitoring, stop_health_monitoring
from app.utils.logging.logger_config import setup_logging

# 设置日志
setup_logging()
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info("Starting Disaster Recovery Service...")

    # 创建数据库表
    Base.metadata.create_all(bind=engine)

    # 启动健康监控
    await start_health_monitoring()

    logger.info("Disaster Recovery Service started successfully")

    yield

    # 关闭时
    logger.info("Shutting down Disaster Recovery Service...")

    # 停止健康监控
    await stop_health_monitoring()

    logger.info("Disaster Recovery Service stopped")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="灾备控制服务 - 提供主备服务监控、故障检测和自动切换功能",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该配置具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Global exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )


# 注册路由
app.include_router(services.router, prefix="/api/v1")


# 健康检查端点
@app.get("/health")
async def health_check():
    """服务健康检查"""
    return {
        "status": "healthy",
        "service": settings.app_name,
        "version": settings.app_version,
        "timestamp": datetime.utcnow().isoformat()
    }


# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "Disaster Recovery Service is running",
        "docs": "/docs",
        "health": "/health"
    }


# 监控状态
@app.get("/monitoring/status")
async def monitoring_status():
    """获取监控状态"""
    from app.services.monitoring.scheduler import get_monitoring_status
    return get_monitoring_status()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )